import {AfterViewInit, Component, OnInit, ViewChild} from '@angular/core';
import {DepartmentsService} from "./departments.service";
import {Router, ActivatedRoute} from "@angular/router";
import {Departments} from "./departments";
import {ResponseUtil} from "../../../util/response-util";
import {MsgResult} from "../../../models/msg-result";
import {Path} from "../../../portal/admin/admin-breadcrumb/breadcrumb";
import {PageSubject} from "../../../util/page-subject";
import {OneDialogService} from "../../../widgets/one-dialog/one-dialog.service";
import {OneOperationComponent} from "../../../widgets/one-operation/one-operation.component";
import {API, MsgConstants} from "../../../constants/constants";
import {TableUtil} from "../../../util/table-util";

declare var $;

@Component({
  selector: 'app-departments',
  templateUrl: './departments.componentv2.html'
})
export class DepartmentsComponent implements OnInit, AfterViewInit {
  @ViewChild(OneOperationComponent) operation: OneOperationComponent;
  //定义部门数组
  departments: Departments[];
  //定义变量id
  id: Array<string> = [];

  message: string;

  deptTypeUrl: string;

  orgTable;

  deptTable;

  treeObj;

  deptType: string;

  typeArr: Array<Object> = [];

  siteTypeName: string;

  siteCategory: Array<Object> = [];

  constructor(private router: Router,
              private route: ActivatedRoute,
              private pageSubject: PageSubject,
              private responseUtil: ResponseUtil,
              private dialogService: OneDialogService,
              private tableUtil: TableUtil,
              private departmentsService: DepartmentsService) {
  }

  proxy = {
    "departmentAdd": () => this.departmentAdd(),
    "departmentDelete": () => this.departmentDelete(),
    "departmentUpdate": () => this.departmentUpdate()
  }

  ngOnInit() {
    //初始化数据
    this.initDepartmentFormData();
    this.pushPage();

    this.loadDeptOrgInfo();//组织机构表格

    this.getLoginAccountInfo();
    this.getSiteType();
    this.getSiteCategory();
  }

  ngAfterViewInit() {
    //操作函数代理
    this.operation.proxy = this.proxy;
  }

  /**
   * 面包屑导航
   */
  pushPage() {
    let path = new Path("权限系统", "");
    this.pageSubject.pushPage("部门管理", "查询", path);
  }

  /**
   * 无参查询
   */
  initDepartmentFormData() {
    this.departmentsService.getDepartments().subscribe(
      result => this.responseUtil.success(result, this.generateDeptDom),
      message => this.responseUtil.error(message)
    );
  }

  /**
   * 添加页面跳转
   */
  departmentAdd() {
    this.router.navigate(['add', {type: this.deptType}], {relativeTo: this.route})
  }

  /**
   * 弹出删除弹窗
   */
  departmentDelete() {
    let rows = this.deptTable.bootstrapTable('getSelections');
    this.id = this.tableUtil.getIds(rows);
    if (this.id.length != 1) {
      this.dialogService.modalInfo("请选择一条数据");
    } else {
      this.dialogService.modalInfoWithCancelBtn("确定删除？", this.requestDelete);
    }
  }

  /**
   * 实现删除操作
   * 1.调取后端删除操作；
   */
  private requestDelete = () => {
    this.departmentsService.deleteDepartment(this.id[0]).subscribe(
      result => this.responseUtil.success(result, this.processDeleteResult),
      error => this.responseUtil.error(error)
    );
  }

  /**
   * 处理删除结果
   * 1.判断是否删除成功；
   * @param result
   */
  private processDeleteResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.dialogService.success(result.message);
      this.searchDept();
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  };

  searchDept() {
    this.deptTable.bootstrapTable('refresh');
  }

  //(暂无使用)
  searchDeptOrg() {
    this.orgTable.bootstrapTable('refresh', {url: this.deptTypeUrl});
  }

  /**
   * 修改页面跳转
   */
  departmentUpdate() {
    let rows = this.deptTable.bootstrapTable('getSelections');
    this.id = this.tableUtil.getIds(rows);
    if (this.id.length != 1) {
      this.dialogService.modalInfo("请选择一条数据");
    } else {
      this.router.navigate(['update', {deptId: this.id, deptType: this.deptType}], {relativeTo: this.route});
    }
  }

  /**
   * 截取部门数据
   * @param result
   */
  private generateDeptDom = (result: MsgResult) => {
    this.departments = result.data;
  }

  /**
   * 部门中的组织机构列表查询(暂无使用)
   */
  loadDeptOrgInfo() {
    this.orgTable = this.tableUtil.load("dept_org_table", {
      columns: [
        {radio: true},
        {field: "id", title: 'ID', align: 'left', visible: false, switchable: false},
        {field: "name", title: '名称', align: 'left', width: '100'}
      ],
      idField: "id",
      sidePagination: 'server',
      pagination: true,
      pageNumber: 1,
      pageSize: 15,
      pageList: [10, 15, 50],
      paginationPreText: "上一页",
      paginationNextText: "下一页",
      paginationLoop: false,//是否开启循环分页
      singleSelect: true,//多选
      clickToSelect: true,//点击选中
      url: API.govPageListV2,
      method: 'post',
      //传递附加参数
      queryParams: (params) => {
        params.name = $("#dept_name").val();
        params.regionCode = $("#dept_org_id").val();
        return params;
      },
      //返回数据处理器
      responseHandler: (result) => {
        return this.responseUtil.bsPageHandler(result, (result) => {
          result.data.rows.forEach(function (value) {
            // value.create_date = value.createDate || '';
          });
        });
      },
      onLoadSuccess: (data) => {
        this.orgTable.bootstrapTable("check", 0);
        $("#dept_org_id").val(data.rows[0].id);
      },
      onCheck: (row) => {
        $("#dept_org_id").val(row.id);
        this.searchDept();
      },
      onUncheck: (row) => {
        $("#dept_org_id").val("");
        this.searchDept();
      },
      toolbar: "#one_operation_departments",
      height: 700,//table高度
      sortable: true,
      order: 'asc',
      sortName: "CREATE_DATE",
      minimumCountColumns: 3,//最少保留显示的列数量
      classes: "table table-hover",
      striped: true,//隔行变色
      mobileResponsive: true//响应式
    });
  }

  /**
   * 部门列表查询
   */
  loadDeptInfo() {
    this.deptTable = this.tableUtil.load("dept_table", {
      columns: [
        {checkbox: true},
        {field: "id", title: 'ID', align: 'left', visible: false, switchable: false},
        {field: "name", title: '名称', align: 'left'},
        {field: "siteType", title: '站点类型', align: 'left', formatter: this.hyperlinkFormat},
        {field: "isValid", title: '有效', align: 'left', formatter: this.yesOrNoFormat}
      ],
      idField: "id",
      sidePagination: 'server',
      pagination: true,
      pageNumber: 1,
      pageSize: 15,
      pageList: [10, 15, 50],
      paginationPreText: "上一页",
      paginationNextText: "下一页",
      paginationLoop: false,//是否开启循环分页
      singleSelect: false,//多选
      clickToSelect: true,//点击选中
      url: API.deptPageListV2,
      method: 'post',
      //传递附加参数
      queryParams: (params) => {
        params.name = $("#dept_name").val();
        params.orgId = $("#dept_org_id").val();
        params.pId = $("#dept_pId").val();
        return params;
      },
      //返回数据处理器
      responseHandler: (result) => {
        return this.responseUtil.bsPageHandler(result, (result) => {
          result.data.rows.forEach(function (value) {
            // value.create_date = value.createDate || '';
            value.pid = value.pId;
          });
        });
      },
      height: 700,//table高度
      toolbar: "#one_operation_departments",
      sortable: true,
      order: 'asc',
      sortName: "CREATE_DATE",
      showColumns: true,//显示自定义显示列按钮
      showRefresh: true,//显示刷新按钮
      minimumCountColumns: 3,//最少保留显示的列数量
      showToggle: true,//显示视图切换按钮
      showPaginationSwitch: true,//显示是否分页切换按钮
      classes: "table table-hover",
      striped: true,//隔行变色
      mobileResponsive: true//响应式
    });
    this.tableUtil.bindResetTableView(this.deptTable);
  }

  /**
   * 超链接提示格式化函数
   * @param value
   * @param row
   * @param index
   * @returns {any}
   */
  private hyperlinkFormat(value, row, index) {
    let html = '';
    if('undefined' === value){
      return  html ;
    }

    if (!!value) {
      let siteTypeArr = value.split(",");
      for (let siteType of siteTypeArr) {
        html += '<a href="javascript:void(0)" class="one-mouse-title" data-toggle="tooltip" data-placement="bottom"  style="margin-left:10px;">' + siteType + '</a>';
      }
      return html;
    }
  }


  getSiteType() {
    $("#dept_table").on("mouseenter", ".one-mouse-title", function (e) {
      this.siteTypeName = this.siteCategory[$(e.target).html()];
      $(e.target).attr("data-original-title", this.siteTypeName);
    }.bind(this))

  }

  getSiteCategory() {
    this.departmentsService.getSiteCategory().subscribe(
      result => this.responseUtil.success(result, this.processSiteTypeResult),
      error => this.responseUtil.error(error)
    )
  }

  /**
   *
   * @param result
   */
  processSiteTypeResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.siteCategory = result.data;
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }


  /**
   * yesOrNo格式化函数
   * @param value
   * @param row
   * @param index
   * @returns {any}
   */
  private yesOrNoFormat(value, row, index) {
    if (value == '1') {
      return '是';
    }
    if (value == '0') {
      return '否';
    }
  }

  /**
   * 部门类型改变事件
   */
  deptTypeChange = (elem) => {
    if (elem.value == "2") {
      this.deptTypeUrl = API.govPageListV2;
      this.deptType = "2";
    } else if (elem.value == "1") {
      this.deptTypeUrl = API.entInfoPageListV2;
      this.deptType = "1";
    }
    this.getDepartmentTree();
  };

  /**
   * 获取用户信息
   */
  getLoginAccountInfo() {
    this.departmentsService.getLoginAccountType().subscribe(
      result => this.responseUtil.success(result, this.processGetResult),
      error => this.responseUtil.error(error)
    )
  }

  private processGetResult = (result) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      if (result.data == null) {
        this.typeArr.push({type: "2", name: "政府"}, {type: "1", name: "企业"});
        this.deptType = "2";
      } else if (result.data.type == "1") {
        this.typeArr.push({type: "1", name: "企业"});
        this.deptType = "1";
      } else if (result.data.type == "2") {
        this.typeArr.push({type: "2", name: "政府"});
        this.deptType = "2";
      } else {
        this.typeArr.push({type: "2", name: "政府"}, {type: "1", name: "企业"});
        this.deptType = "2";
      }
      //初始化树
      this.getDepartmentTree();
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  /**
   * 获取组织机构与部门树
   */
  getDepartmentTree() {
    this.departmentsService.getDepartmentOrgTree(this.deptType, "").subscribe(
      result => this.responseUtil.success(result, this.processRegionsTreeResult),
      message => this.responseUtil.error(message)
    );
  }

  /**
   * 对行政区划树结果处理
   * @param result
   */
  private processRegionsTreeResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      //初始化zTree
      this.regioCodezTree(result.data);
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  regioCodezTree(data) {
    //    zTreee
    let setting = {
      callback: {
        onClick: this.clickTree
      },
      // check:{
      //   enable:"true",
      //   chkStyle:"radio",
      //   radioType:'all'
      // }(暂无使用)
    };

    let zNodes = data;

    this.treeObj = $.fn.zTree.init($("#dept_ZTree"), setting, zNodes);
    let nodes = this.treeObj.getNodes();
    if (nodes.length > 0) {
      this.treeObj.selectNode(nodes[0]);
      $("#dept_org_id").val(nodes[0].id);
      this.loadDeptInfo();
    }
  }

  clickTree = (event, treeId, treeNode) => {
    let orgId = $("#dept_org_id");
    let entId = $("#dept_pId");
    if (treeNode.hasOwnProperty("orgId")) {
      entId.val(treeNode.id);
      orgId.val(treeNode.orgId);
    } else {
      orgId.val(treeNode.id);
      entId.val("");
    }
    this.searchDept();
  };

}
